package com.yunkaweilai.android.utils;

import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.Html;
import android.text.format.DateFormat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.github.lazylibrary.util.StringUtils;
import com.google.gson.Gson;
import com.yunkaweilai.android.R;
import com.yunkaweilai.android.activity.login.LoginActivity;
import com.yunkaweilai.android.base.BaseApplication;
import com.yunkaweilai.android.constants.Api;
import com.yunkaweilai.android.model.CodeMsgBean;
import com.yunkaweilai.android.model.CodeMsgBean1;
import com.yunkaweilai.android.model.login.UserInfoModel;
import com.yunkaweilai.android.net.Glide.GlideUtils;
import com.yunkaweilai.android.net.HttpRequest;
import com.yunkaweilai.android.net.PostProcess;
import com.yunkaweilai.android.view.MyToast;
import com.yunkaweilai.android.view.dialog.NoTimeDialog;
import com.yunkaweilai.android.view.popup.ImageEnlagePopup;

import java.io.InputStream;
import java.security.MessageDigest;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Administrator on 2017-02-24.
 */

public class Utils {
    private static int spaceTime = 500;//时间间隔

    /**
     * 字符串复制到剪贴板
     *
     * @param context
     * @param text
     */
    public static void copy2clipboard(Context context, String text) {
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("clip", text);
        cm.setPrimaryClip(clip);
    }

    /**
     * 手指点击是否太快
     *
     * @return true点击得太快了，false没有太快
     */
    public static boolean isFastClick() {
        long currentTime = System.currentTimeMillis();//当前系统时间
        boolean isAllowClick;//是否允许点击
        if (currentTime - lastClickTime > spaceTime) {
            isAllowClick = false;
        } else {
            isAllowClick = true;
        }
        lastClickTime = currentTime;
        return isAllowClick;
    }

    /**
     * 添加Fragment到Activity
     *
     * @param fragmentManager
     * @param fragment
     * @param frameId
     */
    public static void addFragmentToActivity(FragmentManager fragmentManager,
                                             Fragment fragment, int frameId) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.add(frameId, fragment);
        transaction.commit();
    }


    /**
     * 获取屏幕的宽度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获取屏幕的高度
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 得到状态栏高度
     *
     * @param context
     * @return
     */
    public static int getStatusBarHeight(Context context) {
        int result = -1;
        //获得状态栏高度资源的id
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }


    /**
     * 从assets 文件夹中获取文件并读取数据
     *
     * @param fileName 文件
     * @param context
     * @return
     */
    public static String getFromAssets(String fileName, Context context) {
        String result = "";
        try {
            InputStream in = context.getResources().getAssets().open(fileName);
            //获取文件的字节数
            int lenght = in.available();
            //创建byte数组
            byte[] buffer = new byte[lenght];
            //将文件中的数据读到byte数组中
            in.read(buffer);

            result = new String(buffer, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 网络是否链接
     *
     * @param context
     * @return
     */
    public static Boolean isNetConnected(Context context) {
        ConnectivityManager manager = (ConnectivityManager) context
                .getApplicationContext().getSystemService(
                        Context.CONNECTIVITY_SERVICE);
        if (manager == null) {
            return false;
        }
        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        if (networkinfo == null || !networkinfo.isAvailable()) {
            return false;
        }
        return true;
    }


    /**
     * 动态设置ListView的高度
     *
     * @param listView
     */
    public static void showPartListView(ListView listView) {
        if (listView == null) return;
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        int size = listAdapter.getCount();

        for (int i = 0; i < size; i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (size - 1));
        listView.setLayoutParams(params);
    }

    //对网络请求的code进行校验
    public static boolean checkCode(String json) {
        Gson gson = new Gson();
        CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
        if (codeMsgBean.getLoginCode() == 0) {
        } else {
            if (codeMsgBean.getCode() == 0) {
            } else if (codeMsgBean.getCode() == 1) {
                return true;
            } else if (codeMsgBean.getCode() == 2) {

            }
        }
        return false;
    }


    //对网络请求的code进行校验
    public static boolean checkCodeNoLogin(final Context context, String json) {
        if (context != null) {
            Gson gson = new Gson();
            CodeMsgBean1 codeMsgBean = gson.fromJson(json, CodeMsgBean1.class);
            if (codeMsgBean.getLoginCode() == 0) {
            } else {
                if (codeMsgBean.getCode() == 0) {
                    MyToast.showShortToast(context, codeMsgBean.getMessage());
                } else if (codeMsgBean.getCode() == 1) {
                    return true;
                } else if (codeMsgBean.getCode() == 2) {
                    final MaterialDialog dialog = new MaterialDialog.Builder(context)
                            .customView(R.layout.dialog_update_app_beiyong, false).cancelable(false)
                            .build();
                    View customView = dialog.getCustomView();
                    TextView idTvUpdateContent = (TextView) customView.findViewById(R.id.id_tv_content);
                    idTvUpdateContent.setText(Html.fromHtml(codeMsgBean.getMessage()));
                    final String url = codeMsgBean.getData().getUrl();
                    Button idBtnUpdate = (Button) customView.findViewById(R.id.id_tv_right);
                    idBtnUpdate.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (!StringUtils.isEmpty(url)) {
                                Uri url1 = Uri.parse(url);
                                Intent intent = new Intent(Intent.ACTION_VIEW, url1);
                                context.startActivity(intent);
                            }
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                }
            }
        }
        return false;
    }

    //对网络请求的code进行校验
    public static boolean checkCode(Context context, String json) {
        if (context != null) {
            Gson gson = new Gson();
            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
            if (codeMsgBean.getLoginCode() == 0) {
                context.startActivity(new Intent(context, LoginActivity.class));
                MyToast.showShortToast(context, codeMsgBean.getMessage());
            } else {
                if (codeMsgBean.getCode() == 0) {
                    MyToast.showShortToast(context, codeMsgBean.getMessage());
                } else if (codeMsgBean.getCode() == 1) {
                    return true;
                } else if (codeMsgBean.getCode() == 2) {
                    NoTimeDialog dialog = new NoTimeDialog(context, codeMsgBean.getMessage());
                    dialog.show();
                }
            }
        }
        return false;
    }

    //对短信网络请求的code进行校验
    public static boolean checkCode(Context context, String json, String x) {
        if (context != null) {
            Gson gson = new Gson();
            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
            if (codeMsgBean.getLoginCode() == 0) {
                context.startActivity(new Intent(context, LoginActivity.class));
            } else {
                if (codeMsgBean.getCode() == 0) {
                } else if (codeMsgBean.getCode() == 1) {
                    return true;
                } else if (codeMsgBean.getCode() == 2) {
                    NoTimeDialog dialog = new NoTimeDialog(context, codeMsgBean.getMessage());
                    dialog.show();
                }
            }
        }

        return false;
    }

    //商品添加验证条码时提示。错误的时候提示
    public static boolean checkCode(Context context, String json, boolean istoast) {
        Gson gson = new Gson();
        CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
        if (codeMsgBean.getLoginCode() == 0) {
            context.startActivity(new Intent(context, LoginActivity.class));
            if (istoast) {
                MyToast.showShortToast(context, codeMsgBean.getMessage());
            }
        } else {
            if (codeMsgBean.getCode() == 0) {
                return true;
            }
        }
        return false;
    }

    //对网络请求的code进行校验,专门检验接口错误的
    public static boolean checkCodeNoToast(Context context, String json) {
        if (json.equals("您使用的私钥格式错误，请检查RSA私钥配置")){
            NoTimeDialog dialog = new NoTimeDialog(context, json);
            dialog.show();
            return false;
        }
        if (context != null) {
            Gson gson = new Gson();
            CodeMsgBean codeMsgBean = gson.fromJson(json, CodeMsgBean.class);
            if (codeMsgBean.getLoginCode() == 0) {
                context.startActivity(new Intent(context, LoginActivity.class));
            } else {
                if (codeMsgBean.getCode() == 1) {
                    return true;
                } else if (codeMsgBean.getCode() == 2) {
                    NoTimeDialog dialog = new NoTimeDialog(context, codeMsgBean.getMessage());
                    dialog.show();
                }
            }
        }

        return false;
    }
//    //对网络请求的code,并检验data中的infoRs参数进行校验
//    public static boolean checkCodeInfoRs(Context context,String json){
//        Gson gson = new Gson();
//        CodeMsgInfoRsBean codeMsginfoBean = gson.fromJson(json, CodeMsgInfoRsBean.class);
//        if (codeMsginfoBean.getLoginCode() == 0){
//            context.startActivity(new Intent(context,LoginActivity.class));
//            MyToast.showShortToast(context,codeMsginfoBean.getMessage());
//        }else{
//            if (codeMsginfoBean.getCode() == 0){
//                MyToast.showShortToast(context,codeMsginfoBean.getMessage());
//            }else if (codeMsginfoBean.getCode() == 1) {
//                if (codeMsginfoBean.getData().isInfoRs()){
//                    return true;
//                }else {
//                    MyToast.showShortToast(context,"未查到数据");
//                }
//            }
//        }
//        return false;
//    }

    /**
     * 得到当年当月的最大日期
     **/
    public static int MaxDayFromDay_OF_MONTH(int year, int month) {
        Calendar time = Calendar.getInstance();
        time.clear();
        time.set(Calendar.YEAR, year);
        time.set(Calendar.MONTH, month - 1);//注意,Calendar对象默认一月为0
        int day = time.getActualMaximum(Calendar.DAY_OF_MONTH);//本月份的天数
        return day;
    }


    /***
     * md5加密
     * @param str
     * @return
     */
    public static String getMD5Str(String str) {
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

        byte[] byteArray = messageDigest.digest();
        StringBuffer md5StrBuff = new StringBuffer();

        for (int i = 0; i < byteArray.length; i++) {
            if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                md5StrBuff.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
            } else {
                md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
            }
        }
        return md5StrBuff.toString().toLowerCase();
    }

    public static void RefreshUserInfo() {
        HttpRequest.postUrl(Api.INIT_USER_INFO)
                .execute(new PostProcess.StringCallBack() {
                    @Override
                    public void onResponse(String json) {
                        boolean checkCode = Utils.checkCode(json);
                        if (checkCode) {
                            Gson gson = new Gson();
                            UserInfoModel userInfoModel = gson.fromJson(json, UserInfoModel.class);
                            BaseApplication.userInfo = userInfoModel.getData().getStoreEmployeeInfo();
                        }
                    }

                    @Override
                    public void onError(Exception e) {

                    }
                });
    }

    /**
     * 清空数据
     */
    public static void cleanBaseApplication() {
        BaseApplication.shiftModel = null;
        BaseApplication.selectedMaps.clear();
        BaseApplication.payModel = null;
        BaseApplication.token = "";
        BaseApplication.userInfo = null;
    }

    /**
     * 金额处理
     */
    public static String ManageMoney(String price) {
        float v = Float.parseFloat(price);
        if (v <= 0) {
            return "0.00";
        } else {
            int i = price.indexOf(".");
            if (i == -1) {
                price = price + ".00";
            } else if (price.length() - i > 2) {
                price = price.substring(0, i + 3);
            } else if (price.length() - i == 2) {
                price = price + "0";
            }
            return price;
        }

    }

    /**
     * 数量处理
     */
    public static String ManageCount(String price) {
        float v = Float.parseFloat(price);
        if (v <= 0) {
            return "0.0";
        } else {
            int i = price.indexOf(".");
            if (i == -1) {
                price = price + ".0";
            } else if (price.length() - i > 2) {
                price = price.substring(0, i + 3);
            } else if (price.length() - i == 2) {
                price = price;
            }
            return price;
        }

    }

    /**
     * 加载会员头像
     *
     * @param context
     * @param member_adv
     * @param sex
     * @param idImgHead
     */

    public static void MemberHeadImg(Context context, String member_adv, String sex, ImageView idImgHead) {
        if (StringUtils.isEmpty(sex) || "male".equals(sex)) {
            if (StringUtils.isEmpty(member_adv)) {
                GlideUtils.loadImage(context, R.mipmap.ic_head_man, idImgHead);
            } else if (member_adv.contains("http")) {
                GlideUtils.loadCircleImage(context, member_adv, idImgHead, true);
            } else {
                GlideUtils.loadCircleImage(context, Api.BASE_URL + member_adv, idImgHead, true);
            }
        } else {
            if (StringUtils.isEmpty(member_adv)) {
                GlideUtils.loadImage(context, R.mipmap.ic_head_woman, idImgHead);
            } else if (member_adv.contains("http")) {
                GlideUtils.loadCircleImage(context, member_adv, idImgHead, false);
            } else {
                GlideUtils.loadCircleImage(context, Api.BASE_URL + member_adv, idImgHead, false);
            }
        }
    }

    /**
     * 图片放大统一方法
     *
     * @param
     * @param type 1会员，2商品
     * @param url
     * @param sex
     */
    public static void ImageEnlage(Activity mAc, String type, String url, String sex) {
        ImageEnlagePopup popup = null;
        if (!StringUtils.isEmpty(url)) {
            if ("1".equals(type)) {
                if (url.contains("http")) {
                    if ("male".equals(sex)) {
                        popup = new ImageEnlagePopup(mAc, url, R.mipmap.ic_head_man);
                    } else {
                        popup = new ImageEnlagePopup(mAc, url, R.mipmap.ic_head_woman);
                    }
                } else {
                    if ("male".equals(sex)) {
                        popup = new ImageEnlagePopup(mAc, Api.BASE_URL + url, R.mipmap.ic_head_man);
                    } else {
                        popup = new ImageEnlagePopup(mAc, Api.BASE_URL + url, R.mipmap.ic_head_woman);
                    }
                }
                popup.showPopupWindow();
            } else if ("2".equals(type)) {
                if (url.contains("http")) {
                    popup = new ImageEnlagePopup(mAc, url, R.mipmap.ic_shop_error);
                } else {
                    popup = new ImageEnlagePopup(mAc, Api.BASE_URL + url, R.mipmap.ic_shop_error);
                }
                popup.showPopupWindow();
            }
        }
    }

    /**
     * 商品图片加载
     *
     * @param context
     * @param url
     * @param idShopImg
     */
    public static void shopInfoImg(Context context, String url, ImageView idShopImg) {
        if (StringUtils.isEmpty(url)) {
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.ic_img_loading)
                    .error(R.mipmap.ic_shop_error_hui);
            Glide.with(context)
                    .load(R.mipmap.ic_shop_error_hui)
                    .apply(options)
                    .into(idShopImg);//图片
        } else {
            RequestOptions options = new RequestOptions()
                    .placeholder(R.mipmap.ic_img_loading)
                    .error(R.mipmap.ic_shop_error_hui);
            Glide.with(context)
                    .load(url)
                    .apply(options)
                    .into(idShopImg);//图片
        }
    }

    /**
     * 会员列表姓名和手机号
     *
     * @param name
     * @param tel
     * @param member_name
     */
    public static void memberNameSet(String name, String tel, TextView member_name) {
        if (StringUtils.isEmpty(tel)) {
            if (!StringUtils.isEmpty(name)) {
                member_name.setText(name);
            } else {
                member_name.setText("");
            }
        } else {
            if (!StringUtils.isEmpty(name)) {
                member_name.setText(name + "  " + tel);
            } else {
                member_name.setText(tel);
            }
        }
    }

    /**
     * 会员列表姓名和手机号和状态
     *
     * @param name
     * @param tel
     * @param member_name
     */
    public static void memberNameSet(String name, String tel, TextView member_name, String status) {
        if (StringUtils.isEmpty(tel)) {
            if (!StringUtils.isEmpty(name)) {
                member_name.setText(Html.fromHtml(name + "&nbsp;&nbsp;" + status));
            } else {
                member_name.setText(Html.fromHtml(status));
            }
        } else {
            if (!StringUtils.isEmpty(name)) {
                member_name.setText(Html.fromHtml(name + "&nbsp;&nbsp;" + tel + "&nbsp;&nbsp;" + status));
            } else {
                member_name.setText(Html.fromHtml(tel + "&nbsp;&nbsp;" + status));
            }
        }
    }

    /**
     * 日期加减。
     *
     * @param days 增加天数(减天数则用负数)
     * @return 计算结果
     */
    public static String datePlus(int days) {
        Calendar cal = Calendar.getInstance();
//        cal.setTime(base);
        cal.add(Calendar.DATE, days);

        return convDate2Str(cal.getTime(), "yyyy-MM-dd");
    }

    /**
     * 将日期转换成指定格式的字符串。
     *
     * @param date   日期
     * @param format 输出格式
     * @return 日期字符串
     */
    public static String convDate2Str(Date date, String format) {
        if (date == null) {
            return "";
        }
        return DateFormat.format(format, date).toString();
    }

    /**
     * 弹出软键盘
     *
     * @param editText
     */
    public static void autoShowKeyboard(final EditText editText) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(editText, 0);
            }
        }, 200);
    }

    /**
     * 1.0 2.0  取整为1，2
     *
     * @return
     */
    public static String MoneyQuZheng(String money) {
        String one = money + "";
        if (one.indexOf(".") > 0) {
            String two = one.substring(one.indexOf("."));
            if (".00".equals(two)) {
                return one.substring(0, one.indexOf("."));
            } else if (".0".equals(two)) {
                return one.substring(0, one.indexOf("."));
            } else {
                return one;
            }
        } else {
            return one;
        }
    }

    /**
     * 1.0 2.0  取整为1，2
     *
     * @return
     */
    public static String MoneyQuZheng(Double money) {
        String one = money + "";
        if (one.indexOf(".") > 0) {
            String two = one.substring(one.indexOf("."));
            if (".00".equals(two)) {
                return one.substring(0, one.indexOf("."));
            } else if (".0".equals(two)) {
                return one.substring(0, one.indexOf("."));
            } else {
                return one;
            }
        } else {
            return one;
        }
    }


    public static boolean isEmpty(CharSequence str) {

        return (str == null || str.length() == 0 || "null".equals(str));
    }

    public static final int DELAY = 1000;
    private static long lastClickTime = 0;

    public static boolean isNotFastClick() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastClickTime > DELAY) {
            lastClickTime = currentTime;
            return true;
        } else {
            return false;
        }
    }

}
